<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/11/6
 * Time: 1:30 PM
 */

namespace App\Library\User;


use App\Events\UserEvent;
use App\Models\User;
use App\Models\UserGroup;

class UserGroupManager
{
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * @param User $user
     */
    public static function upgrade(User $user)
    {
        $manage = new static($user);

        $wallet = $manage->user->wallet()->firstOrCreate([]);
        $group = UserGroup::userGroups()->where('creditslower', '<=', $wallet->total_cost)
            ->where('creditshigher', '>', $wallet->total_cost)->first();
        if ($group)
        {
            if ($group->gid != $user->gid)
            {
                $user->gid = $group->gid;
                $user->save();

                event(new UserEvent($user, 'upgrade'));
            }
        }
    }
}
